<?php
  error_reporting(E_ALL);
  class OCRbreaker {
    function read($data) {
	$orig  = imagecreatefromstring($data);
	$letter_num = 2;

	$pos = array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
	$code = '';
	$lbl = "";
	$hasil = array();
	foreach ($pos as $p1) {
		foreach ($pos as $p2) {
			$lbl = $p1.$p2;
			$gbr = $this->gambar($lbl);
			$skor = $this->beda($orig, $gbr);
			$hasil[$lbl] = $skor;
		}
	}
	asort($hasil);
	foreach ($hasil as $k=>$v) { $kode = $k; break; }
    	return $kode;
  }

  function ketengah($image, $image_width, $string, $font_size, $y, $color) { 
	$text_width = imagefontwidth($font_size)*strlen($string); 
	$center = ceil($image_width / 2); 
	$x = $center - (ceil($text_width/2)); 
	ImageString($image, $font_size, $x, $y, $string, $color); 
  } 
  function gambar($teks) {
	$width = 30;
	$height = 20;

	$image = ImageCreate($width, $height);
	$black = ImageColorAllocate($image, 0, 0, 0);
	$white = ImageColorAllocate($image, 255, 255, 255);
	$grey = ImageColorAllocate($image, 200, 200, 200);
	ImageFill($image, 0, 0, $white);
	$this->ketengah($image, $width, $teks, 3, 3, $black);
	ImageRectangle($image,0,0,$width-1,$height-1,$grey);
	return $image;
  }
  function gambar_canvas($teks) {
	$img = $this->gambar($teks);
	header("Content-Type: image/jpeg");
	ImageJpeg($img);
	ImageDestroy($img);
  }

  function beda($i1, $i2) {
	$sx1 = imagesx($i1);
	$sy1 = imagesy($i1);

	if ($sx1 !== imagesx($i2) || $sy1 !== imagesy($i2)) {
	    return 100;
	}

	$diffi = imagecreatetruecolor($sx1, $sy1);
	$green = imagecolorallocate($diffi, 0, 255, 0);
	imagefill($diffi, 0, 0, imagecolorallocate($diffi, 0, 0, 0));

	$different_pixels = 0;

	for ($x = 0; $x < $sx1; $x++) {
	    for ($y = 0; $y < $sy1; $y++) {

	        $rgb1 = imagecolorat($i1, $x, $y);
	        $pix1 = imagecolorsforindex($i1, $rgb1);

	        $rgb2 = imagecolorat($i2, $x, $y);
	        $pix2 = imagecolorsforindex($i2, $rgb2);

	        if ($pix1 !== $pix2) {
	            $different_pixels++;
	            imagesetpixel($diffi, $x, $y, $green);
	        }

	    }
	}

	if (!$different_pixels) {
	    return 0;
	} else {
	    $total = $sx1 * $sy1;
	    return number_format(100 * $different_pixels / $total, 2);
	}
  }
}
?>
